import io from '@hyoga/uni-socket.io';
import { HardInfoObj } from "./type/index";

const socket = io('http://127.0.0.1:7002', {
  query: {},
  transports: [ 'websocket', 'polling' ],
  timeout: 5000,
});


const hardInfoObj:HardInfoObj = {
	timer:null,
  detectionNum:0
};

/**
 * 发送心跳信息
 */
const sendHartMessage = ():void => {
	socket.emit('send_hart_message');
};

/**
 * 初始化心跳定时器
 */
const initHeartTimer = ():void => {
  hardInfoObj.timer = window.setInterval(()=>{
    sendHartMessage();
    hardInfoObj.detectionNum += 1;
    if(hardInfoObj.detectionNum > 5){
      if(hardInfoObj.timer){
        clearInterval(hardInfoObj.timer);
        hardInfoObj.timer = null;
        console.log("断开链接")
      }
    }
  },3000);
}
/**
 * 清空心跳定时器
 */
const clearHeartTimer = ():void => {
  if(hardInfoObj.timer){
    clearInterval(hardInfoObj.timer);
  }
}
socket.on('connect', () => {
  // socket.io 唯一连接id，可以监控这个id实现点对点通讯
  const { id } = socket;
  initHeartTimer();
  socket.on("watch_hart", () => {
    hardInfoObj.detectionNum = 0;
  });
});

